package com.benson.common.creator.service.impl;

import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ObjectUtil;
import com.benson.common.creator.entity.CreatorDataSource;
import com.benson.common.creator.service.IDataSourceService;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * 数据库服务
 *
 * @author zhangby
 * @date 18/2/20 10:00 am
 */
@Service
public class DataSourceServiceImpl implements IDataSourceService {

    /**
     * 获取表数据
     *
     * @param dataSource
     * @return
     */
    @Override
    public List<Dict> getTable(CreatorDataSource dataSource) throws Exception {
        List<Dict> rsList = new ArrayList<>();
        Connection conn = null;
        try {
            Class.forName(dataSource.getDriverClassName());
            conn = DriverManager.getConnection(
                    dataSource.getUrl(),
                    dataSource.getUsername(),
                    dataSource.getPassword()
            );
            //获取数据库的元数据
            DatabaseMetaData dbMetaData = conn.getMetaData();
            //从元数据中获取到所有的表名
            ResultSet rs = dbMetaData.getTables(null, null, null, new String[]{"TABLE"});

            while (rs.next()) {
                if (dataSource.getUrl().contains(rs.getString("TABLE_CAT"))) {
                    rsList.add(Dict.create()
                            .set("table", rs.getString("TABLE_NAME"))
                            .set("description", rs.getString("REMARKS"))
                    );
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            if (ObjectUtil.isNotNull(conn)) {
                conn.close();
            }
        }
        return rsList;
    }
}
